/*
 * @Author: Cao Shixin
 * @Date: 2021-01-29 15:14:34
 * @LastEditors: Cao Shixin
 * @LastEditTime: 2021-05-11 15:35:57
 * @Description:  log存储基本目录划分
 */
import 'dart:io';

import 'package:archive/archive_io.dart';
import 'package:path_provider/path_provider.dart';

import 'log_util.dart';

class LogPath {
  static String? loggerDir;
  /* 核对本地文件
   * 
   * maxFileCount设置的最多文件数量，超过时长的会做清理
   */
  static void checkLoggerFile({num maxFileCount = 7}) {
    getLoggerDir().then((value) {
      var directory = Directory(value);
      if (directory.existsSync()) {
        var fileList = directory.listSync();
        fileList.sort(
            (a, b) => b.statSync().modified.compareTo(a.statSync().modified));
        fileList.asMap().forEach((key, fileSystemEntity) {
          if (key > maxFileCount) {
            fileSystemEntity.delete(recursive: true);
          }
        });
      }
    }).catchError((e) {
      LogUtil.logE('checkLoggerFileError: $e');
    });
  }

  /* 获取log的文件存储目录地址
   * 
   */
  static Future<String> getLoggerDir() async {
    if (loggerDir != null) {
      return loggerDir!;
    }
    late Directory storageDirectory;
    if (Platform.isAndroid) {
      storageDirectory = (await getExternalStorageDirectory())!;
    } else if (Platform.isWindows) {
      storageDirectory = (await getApplicationSupportDirectory());
    } else {
      storageDirectory = await getApplicationDocumentsDirectory();
    }
    return storageDirectory.path + '/log';
  }

  /* 获取压缩之后的文件路径地址（压缩成功返回正确文件路径，失败返回null）
   * 
   * startDateStamp  开始日期
   * endDateStamp    结束日期
   */
  static Future<String?> getLoggerZip(
      {DateTime? startDate, DateTime? endDate}) async {
    var basDir = await LogPath.getLoggerDir();
    var loggerDir = Directory(basDir);
    if (!await loggerDir.exists()) {
      return null;
    }
    var isFilter = false;
    var filtterDitect = Directory(loggerDir.parent.path + '/filter');
    if (startDate != null || endDate != null) {
      isFilter = true;
      if (await filtterDitect.exists()) {
        await filtterDitect.delete(recursive: true);
      }
      await filtterDitect.create(recursive: true);
      var futures = <Future>[];
      loggerDir.listSync().forEach((file) {
        var direName = file.path.split('/').last;
        //兼容之前旧的存储使用，版本1.0.0之前的,
        if (direName.contains('.')) {
          direName = direName.replaceAll('.', '-');
        }
        var fileDate = DateTime.tryParse(direName);
        if (fileDate != null) {
          //年月日文件夹
          var filterFolder = filtterDitect.path + '/' + direName;
          if (startDate != null && endDate != null) {
            if (fileDate.isAfter(startDate) && fileDate.isBefore(endDate)) {
              futures.add(_copyFile(file, filterFolder));
            }
          } else {
            if (startDate != null) {
              if (fileDate.isAfter(startDate)) {
                futures.add(_copyFile(file, filterFolder));
              }
            } else if (fileDate.isBefore(endDate!)) {
              futures.add(_copyFile(file, filterFolder));
            }
          }
        }
      });
      await Future.wait(futures);
    }
    var encoder = ZipFileEncoder();
    var logZipPath = loggerDir.parent.path + '/log.zip';
    var zipFile = File(logZipPath);
    if (await zipFile.exists()) {
      await zipFile.delete(recursive: true);
    }
    try {
      encoder.zipDirectory(isFilter ? filtterDitect : loggerDir,
          filename: logZipPath);
      return logZipPath;
    } catch (e) {
      LogUtil.logE('getLoggerZipError: $e');
      return null;
    }
  }

  static Future _copyFile(FileSystemEntity file, String folderPath) async {
    await Directory(folderPath).create(recursive: true);
    Directory(file.path).listSync().forEach((fileCell) async {
      var fileName = fileCell.path.split('/').last;
      //file内部文件
      await File(fileCell.path).copy('$folderPath/$fileName');
    });
  }
}
